# -*- coding: utf-8 -*-
"""
__mktime__ = '2019/4/15'
__author__ = 'Just'
__filename__ = 'token'
客户端登录 => 获取token + 获取自己的信息
"""
from flask import jsonify, current_app
from app.libs.enums import ClientTypeEnum
from app.libs.error_code import ForbiddenException
from app.libs.redprint import Redprint
from app.libs.token_auth import generate_auth_token, verify_auth_token_info
from app.model.user import User
from app.validators.form import TokenForm, ClientForm


api = Redprint('token')


@api.route('', methods=['POST'])
def get_token():
    """获取token"""
    form = ClientForm().validate_for_api()
    promise = {
        ClientTypeEnum.USER_EMAIL: User.verify_login_by_email,
        ClientTypeEnum.USER_MINA: User.verify_login_by_mina
    }
    if form.type.data not in promise.keys():
        raise ForbiddenException(msg='目前未支持此类型客户端的操作', error_code=1010)
    # 用户info信息
    info = promise[form.type.data](form.account.data, form.password.data)
    # 生成令牌
    token = generate_auth_token(info['uid'], form.type.data,
                                info['scope'], current_app.config['TOKEN_EXPIRATION'])

    token_str = {'token': token.decode('ascii')}
    return jsonify(token_str)


@api.route('/info', methods=['POST'])
def get_token_info():
    """查看token基本信息"""
    form = TokenForm().validate_for_api()
    # 获取 token 里面的信息
    info = verify_auth_token_info(form.token.data)
    return jsonify(info)
